//
//  HMChangeNumberTableViewCell.m
//  HMMarket
//
//  Created by maimaigo3 on 2017/5/31.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMChangeNumberTableViewCell.h"

@interface HMChangeNumberTableViewCell ()<UITextFieldDelegate>

@end

@implementation HMChangeNumberTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    [_reduceBtn addTarget:self action:@selector(reduceNumber) forControlEvents:UIControlEventTouchUpInside];
    [_addBtn addTarget:self action:@selector(addNumber) forControlEvents:UIControlEventTouchUpInside];
    _numberTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

- (void)reduceNumber {
    if ([_numberTextField.text integerValue] > 1) {
        NSInteger number = [_numberTextField.text integerValue];
        number --;
        _numberTextField.text = [NSString stringWithFormat:@"%ld", number];
        if (number == 1) {
            [_reduceBtn setBackgroundImage:[UIImage imageNamed:@"Cart_reduce_low"] forState:UIControlStateNormal];
        }
        if ([_delegate respondsToSelector:@selector(getNumberOfProduct:)]) {
            [_delegate getNumberOfProduct:_numberTextField.text];
        }
    }
}

- (void)addNumber {
    NSInteger number = [_numberTextField.text integerValue];
    number ++;
    if (number == 1) {
        [_reduceBtn setBackgroundImage:[UIImage imageNamed:@"Cart_reduce_low"] forState:UIControlStateNormal];
    } else {
        [_reduceBtn setBackgroundImage:[UIImage imageNamed:@"Cart_reduce_hightlight"] forState:UIControlStateNormal];
    }
    _numberTextField.text = [NSString stringWithFormat:@"%ld", number];
    if ([_delegate respondsToSelector:@selector(getNumberOfProduct:)]) {
        [_delegate getNumberOfProduct:_numberTextField.text];
    }
}


#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([textField.text integerValue] < 1) {
        [HMHUDManager showHUDWithText:@"最少为1"];
        textField.text = @"1";
    } else {
        if ([_delegate respondsToSelector:@selector(getNumberOfProduct:)]) {
            [_delegate getNumberOfProduct:textField.text];
        }
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
